import serial, time



### variables

k = 7.5 # 8 finger 

finger = [1.627985786,
2.280215268,
3.133357067,
4.133864255,
5.160738214,
5.891671266,
6.46632779,
7.131007287,
]

###

def init():
    # initialize finger position
    fp = []
    print "initializing..."
    for d in range(1,89):
        t = time.clock()
        ser.read()
        ini_c = 0
        ini_v = 0.0
        tm = ''
        while time.clock() - t < 0.1 or ini_c == 0:
            t = time.clock()
            tm = ser.read()
            ini_c = ini_c + 1
            ini_v = ini_v + float(tm)
        print d, "\t", ini_v/ini_c

def words(word):
    re = []
    for i in word:
        if i =='q' or i =='a' or i =='z':
           re.append(1) 
        elif i is 'w'or i =='s'or i =='x':
           re.append(2)
        elif i is 'e'or i =='d'or i =='c':
           re.append(3)
        elif i is 'r'or i =='f'or i =='v'or i =='t'or i =='g'or i =='b':
           re.append(4)
        elif i is 'y'or i =='h'or i =='n'or i =='u'or i =='j'or i =='m':
           re.append(5)
        elif i is 'i'or i =='k':
           re.append(6)
        elif i is 'o'or i =='l'or i =='p':
           re.append(7)
    return re 
           


ser = serial.Serial()
ser.baudrate = 9600
ser.port = 0
ser.open()


print "###Initializing... Words to finger"
wordLetters = ["seoul","beijing","tokyo","paris","london","busan","newyork", "berlin","rome","praha", 
               "boston","texas","lyon","madrid","sydney","milan","napoli","vienna"]
wordList = []
for w in wordLetters:
    k = words(w)
    wordList.append(k)
    print w, k


print "\n### Type..."

list = []
it = time.clock()
itr = True
while itr:
    
    ok = ser.read()
    
    t = time.clock()
    c = 0
    d = 0.0
    tmp = 0.0 
    while time.clock() - t < 0.1:
        t = time.clock()
        ccc = float(ser.read())
        d += ccc
        if ccc > finger[7]:
            itr = False
            break
        c = c + 1
        tmp = d/c
    list.append(tmp)
    if list.__len__() > 15:
        break
list.pop()

print 
print "###Sensed values:"
print list


# analyze
print
print "### Differences measured"
def diff(touch, word):
    i = 0
    dif = 0.0
    if touch.__len__() > word.__len__():
        return 9999
    elif touch.__len__() < word.__len__():
        dif = 5
    for t in touch:
        dif = dif + (t-word[i])*(t-word[i])
        i = i +  1
    return dif

min = 9999.0
minIndex = -1
i = 0
for w in wordList:
    s = diff(list, w)
    if s < min:
        min = s
        minIndex = i
    print wordLetters[i], s
    i = i + 1

print 
print "###You typed:"
print wordLetters[minIndex]

ser.close()
